package com.stars.services.impl.system;
import com.github.pagehelper.PageInfo;
import com.stars.entity.system.SysOrgEntity;
import com.stars.services.system.SysOrgAccessServices;
import com.stars.dao.mapper.system.SysOrgMapper;
import com.stars.entity.dto.system.SysOrgDTO;

import java.util.List;
import com.stars.common.base.BaseConstant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.stars.common.SpecialSymbolUtils;
import org.apache.commons.lang3.StringUtils;
import com.stars.common.base.ResultMsg;
import com.stars.entity.ListPage;
import com.github.pagehelper.PageHelper;
import com.stars.services.impl.BaseAccessServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Title: 公司组织架构 业务逻辑
 * @author dj
 * @date 2019-10-12 16:15:41
 * @version V1.0
 *
 */
@Service
public class SysOrgAccessServicesImpl  extends BaseAccessServiceImpl<SysOrgMapper , SysOrgEntity> implements  SysOrgAccessServices {
    @Autowired
    private SysOrgMapper  sysOrgMapper;

    @Override
    public List<SysOrgDTO> findTreeList(SysOrgDTO treeDTO) throws Exception {
        List<SysOrgDTO> treeList = new ArrayList<>();
        if(treeDTO.getNullFlagQuery()){
            treeDTO.setPid(BaseConstant.ROOT);
        }
        treeList = sysOrgMapper.findByTreeList(treeDTO);
        if(treeList.size() < 1){
            return treeList;
        }
        List<SysOrgDTO> list = sysOrgMapper.findTreeList(treeList);
        return getTree(list);
    }

    private List<SysOrgDTO> getTree(List<SysOrgDTO> list) {
        //首先将list转map映射
        Map<String,SysOrgDTO> map = new HashMap<>();
        List<SysOrgDTO> treeList = new ArrayList<>();
        //循环生成Tree
        for (SysOrgDTO dto: list){
            map.put(dto.getId(),dto);
            if(dto.getLayer() < 3){
                dto.setExpanded(true);
            }
            //如果存在父节点，那么获取父节点，并将自己加入父节点
            if(StringUtils.isNoneEmpty(dto.getPid()) && !BaseConstant.ROOT.equals(dto.getPid()) ){
                map.get(dto.getPid()).getChildren().add(dto);
            }else {
                treeList.add(dto);
            }
        }
        return treeList;
    }


    /**
     * 分页查询
     * @param pageNum 查询参数 起始页，大小。
     * @return
     */
    @Override
    public PageInfo<SysOrgDTO> pageList(Integer pageNum, Integer pageSize, SysOrgDTO dto) throws Exception{
        ListPage<SysOrgDTO> listPage = new ListPage<>(pageNum, pageSize, dto);
        PageHelper.startPage(pageNum, pageSize);
        List<SysOrgDTO> list = sysOrgMapper.pageQuerySysOrg(listPage);
        PageInfo<SysOrgDTO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
